package controller;

import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import bean.Customer;
import bean.FundTransaction;
import bean.Model;
import bean.TransactionStatus;
import bean.TransactionType;
import bean.UserType;
import dao.CustomerDAO;
import dao.FundTransactionDAO;
import formBean.DepositCheckForm;

public class DepositCheckAction extends Action {
	private FormBeanFactory<DepositCheckForm> formBeanFactory = FormBeanFactory.getInstance(DepositCheckForm.class);
	private CustomerDAO customerDAO;
	private FundTransactionDAO fundTransactionDAO;
	
	public DepositCheckAction(Model model) {
		this.customerDAO = model.getCustomerDAO();
		this.fundTransactionDAO = model.getFundTransactionDAO();
	}
	
	@Override
	public String getName() {
		return "depositCheck.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		ArrayList<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		
		try {
			DepositCheckForm form = formBeanFactory.create(request);
			request.setAttribute("form", form);
			
			if (!form.isPresent()) {
				return "depositCheck.jsp";
			}
			
			errors.addAll(form.getValidationErrors());
			
			if (errors.size() > 0) {
				return "depositCheck.jsp";
			}
			
			Customer c = customerDAO.lookUpByUsername(form.getCustomerName());
			
			if (c == null) {
				errors.add("No such customer.");
				return "depositCheck.jsp";
			}
			
			FundTransaction t = new FundTransaction();
			t.setCustomer(c);
			t.setAmount(form.getAmount());
			t.setTransactionType(TransactionType.DEPOSIT_CHECK);
			t.setStatus(TransactionStatus.Pending);
			t.setOrderDate(new Date());
			
			if (fundTransactionDAO.createFundTransaction(t)) {			
				request.setAttribute("message", "You have deposited " + form.getAmountString() + " to customer " 
									+ form.getCustomerName() + ". This deposit will be executed after the transition day.");			
				return "employeeConsole.jsp";
			}
			
			errors.add("The operation cannot be executed. Please contact the admin.");	
			return "depositCheck.jsp";
		} catch (FormBeanException e) {
			e.printStackTrace();
			errors.add(e.getMessage());
			return "depositCheck.jsp";
		}		
	}

	@Override
	public UserType getType() {
		// TODO Auto-generated method stub
		return UserType.Employee;
	}
}
